﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics;
using Cngot.Extensions.Trace.Http;

namespace Cngot.Extensions.DependencyInjection
{
    public static class TraceExtensions
    {
        public static IServiceCollection AddHttpTrace(this IServiceCollection service, Action<HttpTraceOption> action = null)
        {
            if (action == null)
            {
                service.Configure<HttpTraceOption>(w => new HttpTraceOption());
            }
            else
            {
                service.Configure(action);
            }
            service.AddTransient<ILogEventPropertyFactory, LogEventPropertyFactory>();
            service.AddScoped<DiagnosticObserver>();

            return service;
        }

        public static IApplicationBuilder UseHttpTrace(this IApplicationBuilder app)
        {
            //app.UseMiddleware<LoggerMiddleware>();

            app.UseMiddleware<HttpMiddleware>();

            app.UseDiagnosticListener((diagnosticListener, serviceProvider) =>
            {
                //链路追踪
                diagnosticListener.SubscribeWithAdapter(serviceProvider.GetRequiredService<DiagnosticObserver>());
            });
            return app;
        }
        internal static IApplicationBuilder UseDiagnosticListener(this IApplicationBuilder app, Action<DiagnosticListener, IServiceProvider> configure)
        {
            using (var scope = app.ApplicationServices.CreateScope())
            {
                var diagnosticListener = app.ApplicationServices.GetRequiredService<DiagnosticListener>();
                //diagnosticListener.SubscribeWithAdapter(scope.ServiceProvider.GetRequiredService<HttpContextDiagnosticObserver>());
                configure(app.ApplicationServices.GetRequiredService<DiagnosticListener>(), scope.ServiceProvider);
            }
            return app;
        }
    }
}
